package com.helloandroid.activitys

import android.content.Intent
import android.view.View
import android.widget.Button
import android.widget.RelativeLayout
import android.widget.Switch
import android.widget.TextView
import androidx.activity.viewModels
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.fake.FakeMainActivity
import com.helloandroid.AppUtil
import com.helloandroid.MainActivity
import com.helloandroid.MyApplication
import com.helloandroid.R
import com.helloandroid.ads.SmallNativeAdUtil
import com.helloandroid.base.BaseActivity
import com.helloandroid.dialogs.LoadingDialog
import com.helloandroid.ext.parseUser
import com.helloandroid.ext.process
import com.helloandroid.msg.Msg
import com.helloandroid.tools.*
import com.helloandroid.tools.GUtils.httpWithTimeOut
import com.helloandroid.tools.Http.asyncHttpReq
import com.helloandroid.vo.User
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.protol.PrivacyPolicyActivity
import com.protol.TermsActivity
import dai.android.util.AndroidUtils
import kotlinx.coroutines.*
import org.json.JSONObject

class LogoutViewModel : ViewModel() {
    fun logout(callback: (Boolean) -> Unit) {

        if (!NetWorkUtil.networkConnected()) {
            AppUtil.toast("请打开网络.")
            callback(false)
            return
        }


        viewModelScope.launch {
            val url = "user/login?sys_bushu=${AppUtil.user.bs_sys}"
            httpWithTimeOut(10 * 1000, suspend {
                asyncHttpReq(url)
            }) { jsonStr ->
                if (jsonStr.isNullOrEmpty()) {
                    callback(false)
                } else {
                    val jsonObj = JSONObject(jsonStr)
                    val parseResult = jsonObj.process(JSONObject::parseUser)
                    if (parseResult.err == 0) {
                        val serverTime = jsonObj.getLong(GUtils.KeyTime)
                        val newUser = parseResult.obj as User
                        newUser.loginTime = serverTime
                        AppUtil.onLoginSuccess(newUser)
                        callback(true)
                    } else {
                        MyLog.info("err:${parseResult.err},msg:${parseResult.msg}")
                        callback(false)
                    }
                }
            }
        }
    }
}

class SettingActivity : BaseActivity() {

    lateinit var shSign: Switch
    lateinit var btnLogout: Button
    lateinit var tvVersionName: TextView
    private val viewModel: LogoutViewModel by viewModels()

    lateinit var rlBtnNotify: RelativeLayout
    lateinit var rlSignNotify: RelativeLayout

    override fun getContentViewResId() = R.layout.activity_setting

    override fun initView() {

        // init views
        tvVersionName = findViewById(R.id.tvVersionName)
        val packInfo = packageManager.getPackageInfo(packageName, 0)
        tvVersionName.text = packInfo.versionName

        rlBtnNotify = findViewById(R.id.rlBtnNotify)
        rlSignNotify = findViewById(R.id.rlSignNotify)

        shSign = findViewById(R.id.shSign)
        shSign.isChecked = MyApplication.app.serverProxy!!.queryPrefFlag(Msg.C2S_Pref_Sign)
        shSign.setOnCheckedChangeListener { _, isChecked ->
            if (isChecked && !AndroidUtils.isNotificationEnabled(this)) {
                XXPermissions.with(this)
                        .permission(Permission.NOTIFICATION_SERVICE)
                        .request { _, _ -> }
            }
            MyApplication.app.serverProxy?.sendMsgToServer(Msg.C2S_Pref_Sign, isChecked.toString())
        }

        findBtn(R.id.ibBack).setOnClickListener {
            finish()
        }

        if (AppConfig.isFake) {
            rlBtnNotify.visibility = View.GONE
            rlSignNotify.visibility = View.GONE
        } else {
            rlBtnNotify.visibility = View.VISIBLE
            rlBtnNotify.setOnClickListener {
                startActivity(Intent(this, NotifySettingActivity::class.java))
            }
            rlSignNotify.visibility = View.VISIBLE
        }

        btnLogout = findViewById(R.id.btnLogout)
        if (AppUtil.user.wx_id.isNullOrBlank()) {
            // 没有绑定微信
            btnLogout.visibility = View.GONE
        } else {
            // 绑定了微信
            btnLogout.visibility = View.VISIBLE
            btnLogout.setOnClickListener {

                // 显示退出登陆
                val loadingDialog = LoadingDialog(this, "处理中...")
                loadingDialog.show()

                viewModel.logout { success ->
                    loadingDialog.dismiss()
                    if (success) {
                        if (AppConfig.isFake) {
                            // 跳转到 FakeMainActivity
                            val intent = Intent(this, FakeMainActivity::class.java)
                            startActivity(intent)
                        } else {
                            // 跳转到MainActivity
                            val intent = Intent(this, MainActivity::class.java)
                            intent.putExtra(IntentKey.ComeFromWhere, IntentValue.Int_Resdient)
                            startActivity(intent)
                        }
                        finish()
                    }
                }
            }
        }

        // 隐私和政策
        findBtn(R.id.btnYinSi).setOnClickListener { startActivity(Intent(this, PrivacyPolicyActivity::class.java)) }
        findBtn(R.id.btnProtol).setOnClickListener { startActivity(Intent(this, TermsActivity::class.java)) }

        SmallNativeAdUtil.showNativeAd(this, findViewById(R.id.nativeView))
    }

    override fun initData() {
    }
}